package cn.dac.shiro.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 验证验证码Filter
 * 配置
 * ShiroConfiguration ShiroFilterFactoryBean
 * 暂时未使用
 * 原因：url频繁访问此过滤器 改为登录Controller时验证
 * @author anan
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {
    private static final Logger logger = LoggerFactory.getLogger(CustomFormAuthenticationFilter.class);
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        // 在这里进行验证码的校验
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();
        // 输入的验证码
        String vrifyCode = httpServletRequest.getParameter("vrifyCode");
        // 取出验证码
        String trueCode = (String) session.getAttribute("trueCode");
        logger.info("###【检查验证码】sessionCode/submitCode:" +trueCode+"=="+vrifyCode);
        // session 为空时 不需要验证
        if(!StringUtils.isBlank(trueCode)) {
            if (StringUtils.isBlank(vrifyCode)) {
                httpServletRequest.setAttribute("code", "03");
                return true;
            } else {

                if (!vrifyCode.toLowerCase().equalsIgnoreCase(trueCode.toLowerCase())){
                    httpServletRequest.setAttribute("code", "03");
                    return true;
                }
            }

        }


        return super.onAccessDenied(request, response);
    }

}
